package cn.zhx.infrastructure.persistent.repository;



import cn.zhx.domain.task.model.entity.TaskEntity;
import cn.zhx.domain.task.respository.ITaskRepository;
import cn.zhx.infrastructure.event.EventPublisher;
import cn.zhx.infrastructure.persistent.dao.ITaskDao;
import cn.zhx.infrastructure.persistent.po.Task;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhx
 * @Date: 2024/07/18
 * @Description:
 **/

@Repository
public class TaskRepository implements ITaskRepository {
    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;

    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        // 查询未发送消息的任务列表。
        List<Task> tasks = taskDao.queryNoSendMessageTaskList();
//        List<TaskEntity> taskEntities = new ArrayList<>(tasks.size());
//        for (Task task : tasks) {
//            TaskEntity taskEntity = new TaskEntity();
//            taskEntity.setUserId(task.getUserId());
//            taskEntity.setTopic(task.getTopic());
//            taskEntity.setMessageId(task.getMessageId());
//            taskEntity.setMessage(task.getMessage());
//            taskEntities.add(taskEntity);
//        }
        return tasks.stream().map(task -> {
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(task.getUserId());
            taskEntity.setTopic(task.getTopic());
            taskEntity.setMessageId(task.getMessageId());
            taskEntity.setMessage(task.getMessage());
            return taskEntity;
        }).collect(Collectors.toList());
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task taskReq = new Task();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(taskReq);
    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task taskReq = new Task();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(taskReq);
    }
}
